<?php

namespace App\Listeners;

use App\Events\WithdrawalEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class WithdrawalListener
{
    protected $config = [];

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        $this->config = config("queue.connections.rabbitmq");
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\WithdrawalEvent  $event
     * @return void
     */
    public function handle(WithdrawalEvent $event)
    {
        try {
            $connect = new AMQPStreamConnection(//建立生产者与mq之间的连接
                $this->config["host"],
                $this->config["port"],
                $this->config["login"],
                $this->config["password"],
                "/"
            );
            $channel = $connect->channel();//在已连接基础上建立生产者与mq之间的通道
            $channel->exchange_declare($this->config["exchange_name"],"direct",false,true,false);//声明初始化交换机
            $channel->queue_declare($this->config["queue"],false,true,false,false);//声明初始化一条队列
            $channel->queue_bind($this->config["queue"],$this->config["exchange_name"]);//将队列与某个交换机进行绑定，并使用路由关键字
            $msgBody = json_encode($event->withdrawal);
            $msg = new AMQPMessage($msgBody,['content_type'=>'text/plain','delivery_mode'=>2]);//生成消息
            $channel->basic_publish($msg,$this->config["exchange_name"]);//推送消息到某个交换机
            $channel->close();
            $connect->close();
        } catch (\Exception $exception) {
            Log::info($exception->getMessage());
        }
    }
}
